package tablet.module_user.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.lib.app.ARouterPathUtils;
import com.lib.app.CodeUtil;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.clear_cache.ClearDataUtils;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.views.circle_image.niv.NiceImageView;
import com.lib.fastkit.views.dialog.http.DialogUtils;
import com.lib.fastkit.views.dialog.normal.CoachAIStudyDialog;
import com.lib.fastkit.views.dialog.zenhui.AlertDialog;
import com.lib.http.call_back.HttpDialogCallBack;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.ui.fragment.BaseAppFragment;
import com.lib.utls.glide.GlideConfig;

import butterknife.BindView;
import butterknife.OnClick;
import tablet.module_user.R;
import tablet.module_user.R2;
import tablet.module_user.bean.LoginOutBean;
import tablet.module_user.bean.StudentWorkRecordBean;
import tablet.module_user.bean.StudnetConnectaBean;
import tablet.module_user.bean.UserInfoBean;

public class StudentInfoRecordFragment_1 extends BaseAppFragment {

    @BindView(R2.id.iv_user)
    NiceImageView ivUser;
    @BindView(R2.id.tv_name)
    TextView tvName;
    @BindView(R2.id.lin_name)
    LinearLayout linName;
    @BindView(R2.id.tv_rest)
    TextView tvRest;
    @BindView(R2.id.tv_num)
    TextView tvNum;
    @BindView(R2.id.lin_ainum)
    LinearLayout linAinum;
    @BindView(R2.id.tv_zan)
    TextView tvZan;
    @BindView(R2.id.tv_flower)
    TextView tvFlower;
    @BindView(R2.id.lin_zanflower)
    LinearLayout linZanflower;

    @BindView(R2.id.lin_kebiao)
    LinearLayout linKebiao;
    @BindView(R2.id.lin_shangcheng)
    LinearLayout linShangcheng;
    @BindView(R2.id.lin_dingdan)
    LinearLayout linDingdan;
    @BindView(R2.id.lin_xiaoxi)
    LinearLayout linXiaoxi;
    @BindView(R2.id.lin_shezhi)
    LinearLayout linShezhi;
    @BindView(R2.id.lin_qingchu)
    LinearLayout linQingchu;

    @BindView(R2.id.tv_classrecord)
    LinearLayout tvClassRecord;
    @BindView(R2.id.lin_luboke)
    LinearLayout linLuboke;
    @BindView(R2.id.lin_jiaofu)
    LinearLayout linJiaofu;
    @BindView(R2.id.lin_teses)
    LinearLayout linTeses;

    UserInfoBean.ObjBean userInfoBean;

    StudentInfoRecordFragment_1 infoRecordFragment;
    private DialogUtils dialogUtils;

    @Override
    protected void onCreateView(View view, Bundle savedInstanceState) {

        infoRecordFragment = this;

        //初始化基础控件和作业记录
//        initBaseViews();

        dialogUtils = new DialogUtils();

        //获取用户信息
        getUserInfo();

    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_student_inforecord_1;
    }


    private void getUserInfo() {

        HttpUtils.with(getActivity())
                .addParam("requestType", "UNIFIED_INTERFACE")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<UserInfoBean>() {
                    @Override
                    public void onSuccess(UserInfoBean result) {

                        if (result.getCode() == CodeUtil.CODE_200) {
                            if (result.getObj() != null) {

                                userInfoBean = result.getObj();

                                initUserView();

                                //设置剩余AI辅导次数
                                if (result.getObj().getSurplus_classes() > -1) {
                                    tvNum.setText(result.getObj().getSurplus_classes() + "次");
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }

    private void initUserView() {

        if (userInfoBean != null) {

            UserInfoBean.ObjBean.PersonalInfoBean personalInfoBean = userInfoBean.getPersonal_info();
            if (StringUtil.isNotEmpty(personalInfoBean.getPhoto_url(), true)) {
                Glide.with(getActivity())
                                                                                                                               .load(personalInfoBean.getPhoto_url())
                        .apply(GlideConfig.getCircleOptions())
                        .into(ivUser);
            }

            if (StringUtil.isNotEmpty(personalInfoBean.getName(), true)) {
                tvName.setText(personalInfoBean.getName());
            }

            if (StringUtil.isNotEmpty(personalInfoBean.getTotal() + "", true)) {
                tvRest.setText(personalInfoBean.getTotal() + "");
            }

            //点赞和鲜花数量
            if (personalInfoBean.getLike_total() > -1) {
                tvZan.setText(personalInfoBean.getLike_total() + "");
            }
            if (personalInfoBean.getRed_flower() > -1) {
                tvFlower.setText(personalInfoBean.getRed_flower() + "");
            }

        }

    }


    @OnClick({R2.id.lin_name,
            R2.id.lin_kebiao, R2.id.lin_shangcheng, R2.id.lin_dingdan,
            R2.id.lin_xiaoxi, R2.id.lin_shezhi, R2.id.lin_qingchu,
            R2.id.tv_classrecord, R2.id.lin_luboke, R2.id.lin_jiaofu, R2.id.lin_teses,})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.lin_name) {

            showNick();
        } else if (i == R.id.lin_shangcheng) {

//            String url = "http://192.168.0.100:8848/flat.html#/mall";

//            String url = "http://192.168.0.10:81/xst_web/flat.html#/mall";

            String url = "https://h5.xuesituedu.com/xst_web/flat.html#/mall";
            ARouter.getInstance().build(ARouterPathUtils.Tablet_App_NormalDetailWebActivity)
                    .withString("urlPath", url).navigation();

        } else if (i == R.id.lin_kebiao) {

            showToast("该功能正在建设中，敬请期待");
        } else if (i == R.id.lin_dingdan) {

            ARouter.getInstance().build(ARouterPathUtils.Tablet_User_OrderListActivity).navigation();

        } else if (i == R.id.lin_xiaoxi) {

            ARouter.getInstance().build(ARouterPathUtils.User_MessageActivity).navigation();

        } else if (i == R.id.lin_shezhi) {

            ARouter.getInstance().build(ARouterPathUtils.User_SetActivity).navigation();
        } else if (i == R.id.lin_qingchu) {//退出------清理数据

            clearTabletCache();
        } else if (i == R.id.tv_classrecord) {

            ARouter.getInstance().build(ARouterPathUtils.User_StudentListDataShowActivity)
                    .withInt("showlistdata", 0).navigation();

        } else if (i == R.id.lin_luboke) {

            ARouter.getInstance().build(ARouterPathUtils.User_StudentListDataShowActivity)
                    .withInt("showlistdata", 1).navigation();

        } else if (i == R.id.lin_jiaofu) {

            ARouter.getInstance().build(ARouterPathUtils.User_StudentListDataShowActivity)
                    .withInt("showlistdata", 2).navigation();

        } else if (i == R.id.lin_teses) {

            ARouter.getInstance().build(ARouterPathUtils.User_StudentListDataShowActivity)
                    .withInt("showlistdata", 3).navigation();

        }
    }


    private void clearTabletCache() {

        CoachAIStudyDialog.getInstance()
                .setTitle("清理缓存")
                .setContent("你确认要缓存么?")
                .setCancelListener(new CoachAIStudyDialog.CancelListener() {
                    @Override
                    public void onCancel() {

                    }
                })
                .setSureListener(new CoachAIStudyDialog.SurelListener() {

                    @Override
                    public void onSure() {
                        dialogUtils.showNormalDialog(getActivity(), "缓存清理中...");

                        ClearDataUtils.clearAllCache(getActivity());
                        ClearDataUtils.cleanWebViewCache(getActivity());

                        /**
                         * 清除 token
                         */
//                        SharedPreferenceManager.getInstance(SetActivity.this).getUserCache().setUserToken("");

                        /**
                         * 清除等待状态
                         */
                        SharedPreferenceManager.getInstance(getActivity()).getUserCache().setIsWait(0);

                        /**
                         * 清除图片缓存
                         * 该方法必须在主线程
                         */
                        Glide.get(getActivity()).clearMemory();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {

                                /**
                                 * 清除图片缓存
                                 * 该方法必须在子线程
                                 */
                                Glide.get(getActivity()).clearDiskCache();

                            }
                        }).start();

                        dialogUtils.dismiss();

                        //清理缓存之后，需要重新登录
//                        ARouter.getInstance().build(ARouterPathUtils.User_LoginActivity).navigation();

                    }


                })
                .show(getChildFragmentManager());

    }

    NickNameFragment nickNameFragment;

    private void showNick() {

        final AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setContentView(R.layout.dialog_nick)
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (nickNameFragment != null) {
                            getActivity().getSupportFragmentManager().beginTransaction().remove(nickNameFragment).commit();
                            nickNameFragment = null;
                        }
                    }
                }).fullWidth()
                .addDefaultAnimation()
                .show();

        nickNameFragment = (NickNameFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_nick);

        nickNameFragment.setOnNomalChangeListener(new NickNameFragment.NormalChangeListener() {
            @Override
            public void onNomalChange(String str) {

                if (StringUtil.isNotEmpty(str, true)) {

                    dialog.dismiss();

                    //将修改的昵称发送到服务器
                    sendChangeNameToService(str);

                } else {
                    showToast("请输入您想要修改的昵称！");
                }
            }
        });
    }

    private void sendChangeNameToService(final String str) {

        HttpUtils.with(getActivity())
                .addParam("requestType", "CHANGE_NAME")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .addParam("name", str)
                .execute(new HttpDialogCallBack<LoginOutBean>() {
                    @Override
                    public void onSuccess(LoginOutBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            showToast("昵称修改成功！");
                            tvName.setText(str);
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }
}
